package db

import ext.log
import manager.DataBaseManager
import org.json.JSONObject
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList


class Cargo(
    val waresId: String, // 商品ID
    val col: Int,
    val row: Int,
    val overdueTimestamp: Long
) { // 商品过期的时间戳

    fun toJson(): JSONObject {
        val json = JSONObject()
        json.put("waresId", waresId)
        json.put("col", col)
        json.put("row", row)
        json.put("overdueTimestamp", overdueTimestamp)
        return json
    }


    companion object {

        const val TABLE_NAME = "db_cargo"

        const val TABLE_CREATE_SQL = "create table if not exists $TABLE_NAME (" +
                "id integer primary key autoincrement, " +
                "wares_id varchar(30), " +
                "col integer, " +
                "row integer, " +
                "overdue_timestamp integer)"

        const val TABLE_INSERT_SQL = "insert into $TABLE_NAME ( " +
                "wares_id, col, row, overdue_timestamp) " +
                "values (?, ?, ?, ?)"

        const val TABLE_QUERY_SQL = "select * from $TABLE_NAME where wares_id = ?"

        const val TABLE_QUERY_MIN_SQL = "select wares_id, col, row, min(overdue_timestamp) " +
                "from $TABLE_NAME " +
                "where wares_id = ? " +
                ""

        const val TABLE_DELETE_SQL = "delete from $TABLE_NAME where col = ? and row = ?"

        const val TABLE_DELETE_ID_SQL = "delete from $TABLE_NAME where wares_id = ?"

        const val TABLE_DELETE_ALL_SQL = "delete from $TABLE_NAME"

        fun withJson(waresId: String, json: JSONObject): Cargo {
            val cargoData = json.getString("cargoData")
            val pastDueTime = json.getString("pastDueTime")
            val sps = cargoData.split("-")
            val col = sps[0].toInt()
            val row = sps[1].toInt()

            val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            format.timeZone = TimeZone.getTimeZone("Asia/Shanghai")
            val date = format.parse(pastDueTime)
            val overdue = date.time
            return Cargo(waresId, col, row, overdue)
        }

        fun createTable() {
            val db = DataBaseManager.Instance.writableDatabase
            db.execSQL(TABLE_CREATE_SQL)
            db.close()
            log("创建货道表")
        }

        fun delete() {
            val db = DataBaseManager.Instance.writableDatabase
            db.execSQL(TABLE_DELETE_ALL_SQL)
            db.close()
            log("货道表全部删除")
        }

        fun deleteByWaresId(waresId: String) {
            val db = DataBaseManager.Instance.writableDatabase
            db.execSQL(TABLE_DELETE_ID_SQL, arrayOf(waresId))
            db.close()
            log("$waresId 货道表全部删除")
        }

        fun queryByWaresId(waresId: String): ArrayList<Cargo> {
            val list = ArrayList<Cargo>()
            val db = DataBaseManager.Instance.readableDatabase
            try {
                val cursor = db.rawQuery(TABLE_QUERY_SQL, arrayOf(waresId))
                while (cursor.moveToNext()) {
                    val waresId2 = cursor.getString(1)
                    val col = cursor.getInt(2)
                    val row = cursor.getInt(3)
                    val overdueTimestamp = cursor.getLong(4)
                    val cargo = Cargo(waresId2, col, row, overdueTimestamp)
                    log("找到了一个货道:$cargo")
                    list.add(cargo)
                }
                cursor.close()
            } catch (e: Exception) {
                e.printStackTrace()
                throw IOException("货道查找错误")
            } finally {
                db.close()
            }
            return list
        }
    }

    val name = "$col-$row"

    fun insert() {
        val db = DataBaseManager.Instance.writableDatabase
        db.execSQL(
            TABLE_INSERT_SQL, arrayOf(
                waresId, col, row, overdueTimestamp
            )
        )
        db.close()
        log("插入货道:${this}")
    }

    fun delete() {
        val db = DataBaseManager.Instance.writableDatabase
        db.execSQL(
            TABLE_DELETE_SQL, arrayOf(
                col, row
            )
        )
        db.close()
        log("删除货道:${this}")
    }

    fun isNotOverdue(): Boolean {
        return System.currentTimeMillis() - overdueTimestamp < 60 * 60 * 1000
    }

    override fun toString(): String {
        return "($waresId $col $row $overdueTimestamp)"
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as Cargo

        if (col != other.col) return false
        if (row != other.row) return false

        return true
    }

    override fun hashCode(): Int {
        var result = col
        result = 31 * result + row
        return result
    }

}
